import { routerApi } from '@/api'
import mainContent from '@/layout'

/**
 * 获取uuid
 */
export function getUUID() {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
		return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' |
			'0x8')).toString(16)
	})
}

/**
 * 动态获取路由
 */

export async function getRoute() {
	let home = [
		{
			path: '/',
			name: '/',
			redirect: '/home',
			component: mainContent,
			children: [
				{
					path: '/home',
					name: '首页',
					icon: 'el-icon-s-home',
					component: () => import('@/views/home/home')
				}
			]
		}]
	let arr = []
	await routerApi.getRouter().then((res) => {
		let list = res.data
		list.forEach(item => {
			let o = {
				id: item.id,
				parentId: item.parentId,
				component: item.component,
				icon: item.icon,
				name: item.name,
				path: item.path
			}
			arr.push(o)
		})
	})
	arr = handleTree(arr)
	arr.forEach(item => {
		let subView = item.component.replace(/^\/*/g, '')//路由组件
		if (item.children) {
			item.children.forEach(child => {
				let subView = child.component.replace(/^\/*/g, '')//路由组件
				child.component = resolve => require([`@/views/${subView}`],
					resolve)
			})
		}
		if (subView.indexOf('routerViews') > -1) {
			item.component = resolve => require([`@/components/${subView}`],
				resolve)
		} else {
			item.component = resolve => require([`@/views/${subView}`], resolve)
		}
	})
	arr.forEach(item => {
		home[0].children.push(item)
	})
	return home
}

/**
 * 排序生成规则
 * @param {*} num 当前数字
 * @param {*} page  第几页
 */
export const numSort = (num, page, pageSize = 10) => {
	num = num + 1
	page = (page * pageSize)
	return (page + num) - pageSize
}
// 防抖
export const debounce = (func, delay) => {
	let timeout
	return function () {
		clearTimeout(timeout) // 如果持续触发，那么就清除定时器，定时器的回调就不会执行。
		timeout = setTimeout(() => {
			func.apply(this, arguments)
		}, delay)
	}
}
// 节流
export const throttle = (func, delay) => {
	let run = true
	return function () {
		if (!run) {
			return // 如果开关关闭了，那就直接不执行下边的代码
		}
		run = false // 持续触发的话，run一直是false，就会停在上边的判断那里
		setTimeout(() => {
			func.apply(this, arguments)
			run = true // 定时器到时间之后，会把开关打开，我们的函数就会被执行
		}, delay)
	}
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
	let config = {
		id: id || 'id',
		parentId: parentId || 'parentId',
		childrenList: children || 'children'
	}

	let childrenListMap = {}
	let nodeIds = {}
	let tree = []

	for (let d of data) {
		let parentId = d[config.parentId]
		if (childrenListMap[parentId] == null) {
			childrenListMap[parentId] = []
		}
		nodeIds[d[config.id]] = d
		childrenListMap[parentId].push(d)
	}

	for (let d of data) {
		let parentId = d[config.parentId]
		if (nodeIds[parentId] == null) {
			tree.push(d)
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t)
	}

	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]]
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c)
			}
		}
	}

	return tree
}

// 刷新权限
export const refreshPermissions = () => {
	console.log('刷新权限')
	permissions = []
	if (localStorage.getItem('permissions')) {
		permissions = localStorage.getItem('permissions').split(',')
	}
}

let permissions = []
export const hasBtnPermission = val => {
	if (permissions.length === 0) {
		permissions = localStorage.getItem('permissions').split(',')
	}
	return permissions.indexOf(val) > -1
}
